package com.usian.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.usian.admin.mapper.UserMapper;
import com.usian.admin.service.UserService;
import com.usian.model.admin.dtos.AdUserDto;
import com.usian.model.admin.pojos.AdUser;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.utils.common.AppJwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;

/**
 * @author baimugudu
 * @email 2415621370@qq.com
 * @date 2023/8/23 15:25
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper,AdUser>
implements UserService {


    /**
     * 登陆成功需要返回token JWT
     * @param adUserDto
     * @return
     */
    public ResponseResult login(AdUserDto adUserDto){
        if(adUserDto==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        if(adUserDto.getName()==null && adUserDto.getPassword()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.USERNAMEORPASSWORDCANNOTNULL);
        }
        String name = adUserDto.getName();

        QueryWrapper<AdUser> objectQueryWrapper = new QueryWrapper<>();
        if(null!=name){
            objectQueryWrapper.lambda().eq(AdUser::getName,name);
        }
        AdUser adUser = this.baseMapper.selectOne(objectQueryWrapper);
        if(null==adUser){
            return ResponseResult.errorResult(AppHttpCodeEnum.ADMIN_USER_NOT_EXIST);
        }else{
            //密文
            String passwordDB = adUser.getPassword();

            log.info("数据库的密文密码：{}",passwordDB);
            //把用户传过来的密码（明文）加密 对比
            //MD5+盐值
            String salt = adUser.getSalt();
            String password = adUserDto.getPassword();
            String passwordNew = DigestUtils.md5DigestAsHex((password + salt).getBytes());
            log.info("当前的密文密码：{}",passwordNew);
            if(passwordDB.equals(passwordNew)){
                //密码正确，登录成功
                Integer userId = adUser.getId();
                HashMap<Object, Object> hashMap = new HashMap<>();
                String token = AppJwtUtil.getToken(userId.longValue());
                hashMap.put("token",token);
                hashMap.put("user",adUser);
                return ResponseResult.okResult(hashMap);
            }else{
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }



        }


    }
}
